package com.zhang.controller;

import com.zhang.domain.Employee;
import com.zhang.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;

@Controller
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    //添加员工
    @RequestMapping(value = "/save",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String save(Employee employee){
        if (employee!=null){
            employeeService.save(employee);
        }
        return "redirect:/employee/findAll";
    }
    //查询
    @RequestMapping("/findAll")
    public ModelAndView findAll(){
        List<Employee> employeeList = employeeService.findAll();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("employeeList",employeeList);
        modelAndView.setViewName("employeeList");
        return modelAndView;
    }

    //修改
    @RequestMapping(value = "/update")
    public String update(int id,int age,String name,String sex, String address){
        Employee employee = new Employee();
        employee.setId(id);
        employee.setAge(age);
        employee.setName(name);
        employee.setSex(sex);
        employee.setAddress(address);
        employeeService.update(employee);
        return "redirect:/employee/findAll";
    }

    //删除员工
    @RequestMapping("delete/{id}")
    public String detele(@PathVariable("id")int id){
        employeeService.delete(id);
        return "redirect:/employee/findAll";
    }

    //根据id回显
    @RequestMapping("/findById/{id}")
    public String  findById(@PathVariable("id") int id, Model model){
        Employee employee = employeeService.findById(id);
        model.addAttribute("employee",employee);
        return "employee";
    }
}
